package com.xc.file.config;

import com.xc.file.enums.FailCode;
import com.xc.file.exception.ResultException;
import com.xc.tool.utils.JSONUtils;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;

import java.io.IOException;

/**
 * <p>项目名称: Stars</p>
 * <p>描述: Feign异常处理</p>
 * <P>创建人:小程 </p>
 * <P>创建人邮箱: 779943476@qq.com</p>
 * <p>创建时间: 2019/11/7</p>
 *
 * @version v1.0
 */
@Slf4j
public class FeignExceptionHandler {
    @Bean
    public ErrorDecoder errorDecoder() {
        return new UserErrorDecoder();
    }

    /**
     * 自定义错误
     */
    public class UserErrorDecoder implements ErrorDecoder {
        @Override
        public Exception decode(String methodKey, Response response) {
            Exception exception = null;
            try {
                // 获取原始的返回内容
                String json = Util.toString(response.body().asReader());
                ResultException result = JSONUtils.getObjectByString(json, ResultException.class);
                exception = FailCode.OTHER_EXCEPTION.exceptionHandle(result.getCode(), result.getMessage());
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                exception = FailCode.FEIGN_REQUEST_ERROR.getServerException();
            }
            return exception;
        }
    }
}
